<template>
  <!-- 承运商表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    top="5%"
    width="1373px"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      :inline="true"
    >
      <el-card
        shadow="never"
        class="table-container mb-[10px] mt-[-10px] p-[70px] pb-[10px] pt-[10px]"
      >
        <el-row>
          <el-form-item label="公司" prop="organizationId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.organizationId"
              placeholder="请输入公司"
              clearable
              @change="changeOrganization"
              style="width: 250px"
              filterable
            >
              <el-option
                v-for="item in organizationList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.organizationCode }}</span>
          </el-form-item>
          <el-form-item label="承运商编号" prop="generalCarrierCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.generalCarrierCode"
              placeholder="请输入承运商编号"
              clearable
              style="width: 250px"
            />
            <span v-else>{{ formData.generalCarrierCode }}</span>
          </el-form-item>
          <el-form-item label="承运商名称" prop="generalCarrierName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.generalCarrierName"
              placeholder="请输入承运商名称"
              clearable
              style="width: 250px"
            />
            <span v-else>{{ formData.generalCarrierName }}</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注">
            <el-input
              v-model="formData.remarks"
              style="width: 1014px"
              type="textarea"
              :rows="3"
              maxlength="255"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-row>
      </el-card>
      <el-tabs v-model="defaultTabValue" type="border-card">
        <el-tab-pane label="司机" :name="1">
          <el-card shadow="never" class="table-container" style="height: 470px">
            <template #header>
              <el-button type="success" plain @click="handleContactAdd">
                <i-ep-plus />
                添加行</el-button
              >
            </template>
            <div class="formTable">
              <el-table
                :data="formData.drivers"
                style="width: 100%"
                :key="Math.random"
                max-height="375px"
                border
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="80px"
                />
                <el-table-column
                  label="司机姓名"
                  align="center"
                  props="driverName"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'drivers.' + $index + '.driverName'"
                      :rules="rules.driverName"
                      style="margin-right: 0"
                    >
                      <el-input
                        v-model="row.driverName"
                        placeholder="请输入司机姓名"
                        style="width: 160px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="司机电话"
                  align="center"
                  props="driverPhone"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'drivers.' + $index + '.driverPhone'"
                      :rules="rules.driverPhone"
                      style="margin-right: 0"
                    >
                      <el-input
                        v-model="row.driverPhone"
                        placeholder="请输入司机电话"
                        style="width: 160px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="司机驾驶证号"
                  align="center"
                  props="driverRegistration"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'drivers.' + $index + '.driverRegistration'"
                      :rules="rules.driverRegistration"
                      style="margin-right: 0"
                    >
                      <el-input
                        v-model="row.driverRegistration"
                        placeholder="请输入司机驾驶证号"
                        style="width: 200px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      :disabled="formData.drivers.length < 2"
                      type="danger"
                      link
                      @click.stop="handleContactDelete(scope.$index)"
                      ><i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="车辆" :name="2">
          <el-card shadow="never" class="table-container" style="height: 470px">
            <template #header>
              <el-button type="success" plain @click="handleProductAdd">
                <i-ep-plus />
                添加行</el-button
              >
            </template>
            <div class="formTable">
              <el-table
                :data="formData.vehicles"
                style="width: 100%"
                :key="Math.random"
                max-height="375px"
                border
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="80px"
                />
                <el-table-column
                  label="车牌号"
                  props="vehicleCode"
                  min-width="150"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'vehicles.' + $index + '.vehicleCode'"
                      :rules="rules.vehicleCode"
                      label-width="0"
                      style="margin-right: 0; margin-left: 23%"
                    >
                      <el-input
                        v-if="!props.isReadonly"
                        v-model="row.vehicleCode"
                        placeholder="请输入车牌号"
                        clearable
                        style="margin-right: 0"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="车辆行驶证号"
                  props="vehicleRegistration"
                  min-width="150"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'vehicles.' + $index + '.vehicleRegistration'"
                      :rules="rules.sonvehicleRegistration"
                      label-width="0"
                      style="margin-right: 0; margin-left: 23%"
                    >
                      <el-input
                        v-if="!props.isReadonly"
                        v-model="row.vehicleRegistration"
                        placeholder="请输入车辆行驶证号"
                        clearable
                      />
                      <span v-else>{{ row.vehicleRegistration }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="车辆类型"
                  props="vehicleTypeId"
                  min-width="150"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'vehicles.' + $index + '.vehicleTypeId'"
                      :rules="rules.vehicleTypeId"
                      style="margin-right: 0; margin-left: 23%"
                    >
                      <el-select
                        v-if="!props.isReadonly"
                        v-model="row.vehicleTypeId"
                        placeholder="请输入车辆类型"
                        clearable
                        @change="changeVehicleType($index, row.vehicleTypeId)"
                        filterable
                      >
                        <el-option
                          v-for="item in vehicleTypeList"
                          :key="item.id"
                          :label="`${item.vehicleTypeCode}-${item.vehicleTypeName}`"
                          :value="item.id"
                        />
                      </el-select>
                      <span v-else>{{ row.vehicleTypeId }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      :disabled="formData.vehicles.length < 2"
                      type="danger"
                      link
                      @click.stop="handleProductDelete(scope.$index)"
                      ><i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { regionData, codeToText, pcaTextArr } from "element-china-area-data";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMPARTNERADDORUPDATE",
  inheritAttrs: false,
});

let defaultTabValue = ref(1);
// 需要联动的数据
const areaOptions = ref(pcaTextArr);
// 需要回显的数据
const selectedOptions = ref([]);
const materials = ref([]);

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const checkMobile = (rule: any, value: any, callback: any) => {
  if (value != "") {
    let reg11 = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (reg11.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确格式电话号"));
    }
  } else {
    callback();
  }
};

const phoneRepeatCheck = (rule: any, value: any, callback: any) => {
  if (value) {
    const details = formData.drivers;
    var findCnt = 0;
    for (let i = 0; i < details.length; i++) {
      const element = details[i];
      if (element.driverPhone === value) {
        findCnt++;
      }
    }
    if (findCnt > 1) {
      return callback(new Error("此手机号已录入"));
    } else {
      callback();
    }
  }
};

const rules = reactive({
  generalCarrierCode: [
    { required: true, message: "请输入承运商编码", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  generalCarrierName: [
    { required: true, message: "请输入承运商名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  organizationId: [
    { required: true, message: "请选择所属公司", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  driverRegistration: [
    { required: true, message: "请输入司机驾驶证号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonvehicleRegistration: [
    { required: true, message: "请输入车辆行驶证号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  driverName: [
    { required: true, message: "请输入司机姓名", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  driverPhone: [
    { required: true, message: "请输入司机联系电话", trigger: "blur" },
    { validator: checkMobile, trigger: "blur" },
    { validator: phoneRepeatCheck, trigger: "blur" },
  ],
  vehicleCode: [
    { required: true, message: "请输入车牌号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  vehicleTypeId: [
    { required: true, message: "请选择车辆类型", trigger: "change" },
  ],
});

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  generalCarrierCode: "",
  generalCarrierName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  vehicles: [
    {
      id: "",
      generalCarrierId: "",
      generalCarrierCode: "",
      vehicleCode: "",
      vehicleRegistration: "",
      vehicleTypeId: "",
      vehicleTypeCode: "",
      vehicleTypeName: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
    },
  ],
  drivers: [
    {
      id: "",
      generalCarrierId: "",
      generalCarrierCode: "",
      driverName: "",
      driverPhone: "",
      driverRegistration: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
    },
  ],
});

const driver = {
  id: "",
  generalCarrierId: "",
  generalCarrierCode: "",
  driverName: "",
  driverPhone: "",
  driverRegistration: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

const vehicle = {
  id: "",
  generalCarrierId: "",
  generalCarrierCode: "",
  vehicleCode: "",
  vehicleRegistration: "",
  vehicleTypeId: "",
  vehicleTypeCode: "",
  vehicleTypeName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

let corpList = ref([]);

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        generalCarrierCode,
        generalCarrierName,
        organizationId,
        organizationCode,
        organizationName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        vehicles,
        drivers,
      } = newVal;
      Object.assign(formData, {
        id,
        generalCarrierCode,
        generalCarrierName,
        organizationId,
        organizationCode,
        organizationName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        vehicles,
        drivers,
      });
      getVehicleTypeList();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.generalCarrierCode = "";
  formData.generalCarrierName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  formData.vehicles = [];
  formData.drivers = [];
}

const loading = ref(false);

/** 联系人添加行 */
const handleContactAdd = () => {
  let sondata = JSON.parse(JSON.stringify(driver));
  formData.drivers.push(sondata);
};

/** 供应产品添加行 */
const handleProductAdd = () => {
  let sondata = JSON.parse(JSON.stringify(vehicle));
  formData.vehicles.push(sondata);
};

/** 联系人删除行 */
const isValidated = ref(false);
const handleContactDelete = (index: any) => {
  formData.drivers.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

/** 供应产品删除行 */
const handleProductDelete = (index: any) => {
  formData.vehicles.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

/** 供应商/客户保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmgeneralcarrier/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getCorpList() {
  const data = await request({
    url: "/mdm/mdmgeneralcarrier/getCorpList",
    method: "get",
  });
  corpList.value = data.data;
}

onMounted(() => {
  getOrganizationList();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//公司列表
const organizationList = ref([]);
const getOrganizationList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 2 },
  });
  organizationList.value = data;
};
const changeOrganization = (id: any) => {
  formData.organizationId = id;
  organizationList.value.forEach((item) => {
    if (item.id === id) {
      formData.organizationCode = item.organizationCode;
      formData.organizationName = item.organizationName;
    }
  });
  getVehicleTypeList();
};

//车辆类型
const vehicleTypeList = ref([]);
const getVehicleTypeList = async () => {
  if (formData.organizationId) {
    const { data } = await request({
      url: "mdm/mdmvehicletype/getVehicleTypeList",
      method: "post",
      data: { organizationId: formData.organizationId },
    });
    vehicleTypeList.value = data;
  }
};
const changeVehicleType = (index: number, id: any) => {
  if (!id) {
    formData.vehicles[index].vehicleTypeId = "";
    formData.vehicles[index].vehicleTypeCode = "";
    formData.vehicles[index].vehicleTypeName = "";
  }
  vehicleTypeList.value.forEach((item: any) => {
    //类型为空是清除信息
    if (item.id == id) {
      formData.vehicles[index].vehicleTypeId = item.id;
      formData.vehicles[index].vehicleTypeCode = item.vehicleTypeCode;
      formData.vehicles[index].vehicleTypeName = item.vehicleTypeName;
    }
  });
};
</script>
